package com.chendx.store.goods.filter;

import com.chendx.model.user.pojo.User;
import com.chendx.store.utils.AppThreadLocalUtils;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by chendx on 2022/4/1.
 */
@Order(1)
@WebFilter(filterName = "appTokenFilter", urlPatterns = "/*")
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 测试和开发环境不过滤
        String userId = request.getHeader("userId");
        String usrename = request.getHeader("username");
        //如果userId为0，说明当前设备没有登录
        if (userId != null && Integer.valueOf(userId).intValue() != 0) {
            User apUser = new User();
            apUser.setId(Integer.valueOf(userId));
            apUser.setUsername(usrename);
            apUser.setHeadPic(StringUtils.isEmpty(request.getHeader("headpic"))?null:request.getHeader("headpic"));
            AppThreadLocalUtils.set(apUser);
        }else {
            AppThreadLocalUtils.set(null);
        }
        filterChain.doFilter(request, response);
    }
}
